﻿using System;
using System.Threading;

using DreamCube.WebServer.WinServiceModel;
using DreamCube.Foundation.Basic.Objects;
using DreamCube.Foundation.Basic.Utility;
using DreamCube.Foundation.Serialization;
using DreamCube.Framework.Utilities.BasicObject;

namespace DreamCube.WebServer.WinService
{
    /// <summary>
    /// 这个是守护windows app的守护进程
    /// </summary>
    internal class KeepWinAppLiveServer : KeepLiveServer
    {
        private void StartApp()
        {
            //MyLog.MakeLog("守护进程重启了服务器！！！！！！！！", MyLog.LogType.Debug, MyLog.LogTarget.SystemLog);
            MyProcess.KillProcessByName(Common.IISProcessName);
            //MyCMD.RunEXE(Common.IISAppPath, "true", 10 * 1000, false);
            CmdRunParameters param = new CmdRunParameters
            {
                FileName = Common.IISAppPath,
                Arguments = "true",
                WaitForExit = false,
                MillisecondTimeOut = 10 * 1000
            };
            MyWeb.PostTo(Common.StartIISPagePath, MyJson.Serialize(param));
        }

        /// <summary>
        /// 检查服务器
        /// </summary>
        public override void DoCheckServer()
        {
            try
            {
                //如果程序退出了，则马上启动程序
                if (!MyProcess.IsExistProcess(Common.IISProcessName))
                {
                    StartApp();
                }
                else
                {
                    try
                    {
                        String result = MyWeb.PostTo(Common.WebLivePagePath, "");
                        if (result != "true")
                            StartApp();
                    }
                    catch (Exception) //如果捕获到异常的话，则重新启动打印服务器
                    {
                        StartApp();
                    }
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }
    }
}
